#include <linux/input.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <termios.h>
#include <errno.h>

#define KEY_EVENT_DEV1_NAME "/dev/input/event5"

#define ECHOFLAGS (ECHO | ECHOE | ECHOK | ECHONL)

int set_disp_mode(int fd, int option){
    int err;
    struct termios term;
    if(tcgetattr(fd, &term) == -1){
        perror("can not get the attribution of the terminal");
        return 1;
    }
    if(option){
        term.c_lflag |= ECHOFLAGS;
    }
    else{
        term.c_lflag &= ~ECHOFLAGS;
    }
    err = tcsetattr(fd, TCSAFLUSH, &term);
    if(err == -1 && err == EINTR){
        perror("can not set the attribution of the terminal");
        return 1;
    }
    return 0;
}


int sysKeyScan(){
    int l_ret = -1;
    int i = 0;
    int key_fd = 0;
    struct input_event key_event = {0};

    key_fd = open(KEY_EVENT_DEV1_NAME, O_RDONLY);
    if(key_fd <= 0){
        perror("open /dev/input/event1 device error");
        return l_ret;
    }

    while(1){
        l_ret = lseek(key_fd, 0, SEEK_SET);
        l_ret = read(key_fd, &key_event, sizeof(key_event));

        if(l_ret){
            if(key_event.type == EV_KEY && key_event.value == 1){
                
                //printf("key %d %s\n", key_event.code, (key_event.value) ? "pressed" : "released");

                if(key_event.code == KEY_ESC){
                    break;
                }
                if(key_event.code == KEY_UP){
                    fprintf(stderr, "\033[1A\033[0m");
                }
                if(key_event.code == KEY_DOWN){
                    fprintf(stderr, "\033[1B\033[0m");
                }
                if(key_event.code == KEY_RIGHT){
                    fprintf(stderr, "\033[1C\033[0m");
                }
                if(key_event.code == KEY_LEFT){
                    fprintf(stderr, "\033[1D\033[0m");
                }
                if(key_event.code == KEY_A){
                    fprintf(stderr, "a");
                }
                if(key_event.code == KEY_D){
                    fprintf(stderr, "d");
                }
            }
        }
    }
    close((key_fd));
    return l_ret;
}

int main(){
    printf("-----------this is a key event test!----------\n");
    printf("          \n");
    printf("          \n");
    printf("          \n");
    printf("          \n");
    printf("          \n");
    printf("          \n");
    printf("          \n");
    fprintf(stderr, "\033[7A\033[0m");
    set_disp_mode(STDIN_FILENO, 0);
    sysKeyScan();
    set_disp_mode(STDIN_FILENO, 1);
    return 0;
}


